闘本 2.1 重複要素の削除
提出
code: txt
def remove_duplicate(a):
return set(a)
解答
code: python
import random
class LinkedListNode:
def __init__(self, value, next_node=None, prev_node=None):
self.value = value
self.next = next_node
self.prev = prev_node
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self, values=None):
self.head = None
self.tail = None
if values is not None:
self.add_multiple(values)
def __iter__(self):
current = self.head
while current:
yield current
current = current.next
def __str__(self):
return " -> ".join(values)
def __len__(self):
result = 0
node = self.head
while node:
result += 1
node = node.next
return result
def values(self):
def add(self, value):
if self.head is None:
self.tail = self.head = LinkedListNode(value)
else:
self.tail.next = LinkedListNode(value)
self.tail = self.tail.next
return self.tail
def add_to_beginning(self, value):
if self.head is None:
self.tail = self.head = LinkedListNode(value)
else:
self.head = LinkedListNode(value, self.head)
return self.head
def add_multiple(self, values):
for v in values:
self.add(v)
@classmethod
def generate(cls, k, min_value, max_value):
return cls(random.choices(range(min_value, max_value), k=k))
class DoublyLinkedList(LinkedList):
def add(self, value):
if self.head is None:
self.tail = self.head = LinkedListNode(value)
else:
self.tail.next = LinkedListNode(value, None, self.tail)
self.tail = self.tail.next
return self
def remove_dups(ll):
current = ll.head
previous = None
seen = set()
while current:
if current.value in seen:
previous.next = current.next
else:
seen.add(current.value)
previous = current
current = current.next
ll.tail = previous
return ll
def remove_dups_followup(ll):
runner = current = ll.head
while current:
runner = current
while runner.next:
if runner.next.value == current.value:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
ll.tail = runner
return ll
def example():
ll = LinkedList.generate(100, 0, 9)
print(ll)
print("======================")
remove_dups(ll)
print(ll)
print("======================")
ll = LinkedList.generate(100, 0, 9)
print(ll)
print("======================")
remove_dups_followup(ll)
print(ll)
if __name__ == "__main__":
example()